package cc.magicjson.design.principles.openclose.thread;

import java.util.concurrent.CountDownLatch;
import java.util.function.IntConsumer;

/**
 * {@link}
 *
 * @author <a href="mailto:it_magicjson@163.com">MagicJson</a>
 * @since 1.0.0
 */
public class MultiThreadPrinter {

	public static void main(String[] args) throws InterruptedException {

		BaseNumberPrinter synchronizedPrinter = new NumberBySynchronizedPrinter(5);

		BaseNumberPrinter reentrantLockPrinter = new NumberByReentrantLockPrinter(5);

		printNumber(synchronizedPrinter);
		System.out.println("=====================");
		printNumber(reentrantLockPrinter);

	}
	private static void printNumber(BaseNumberPrinter baseNumberPrinter) {
		CountDownLatch countDownLatch = new CountDownLatch(3);
		IntConsumer intConsumer = System.out::println;
		Thread zeroThread = new Thread(() -> {
			baseNumberPrinter.printZeroNumber(intConsumer);
			countDownLatch.countDown();
		});
		Thread oddThread = new Thread(() -> {
			baseNumberPrinter.printOddNumber(intConsumer);
			countDownLatch.countDown();
		});

		Thread evenThread = new Thread(() -> {
			baseNumberPrinter.printEvenNumber(intConsumer);
			countDownLatch.countDown();
		});

		zeroThread.start();
		oddThread.start();
		evenThread.start();
		try {
			countDownLatch.await();
		} catch (InterruptedException e) {
			throw new RuntimeException(e);
		}

	}
}
